package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext servletContext;


    @GetMapping
    public Object list() {
        return regionService.list();
    }

    @GetMapping("{state}")
    public Object queryForState(RegionQueryObject qo) {
        return regionService.queryForState(qo);
    }

    @GetMapping(value = "/{placeId}/strategies", produces = "text/html")
    public void queryStrategyByPlaceId(StrategyQueryObject qo, HttpServletResponse response) {
        qo.setPageSize(0);
        PageInfo recommends = strategyService.queryStrategyByPlaceId(qo);
        qo.setState(null);
        qo.setPageSize(8);
        PageInfo all = strategyService.queryStrategyByPlaceId(qo);
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        try {
            configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
            Template template = configuration.getTemplate("template.ftl", "utf-8");
            Map<String, Object> map = new HashMap<>();
            map.put("recommends", recommends);
            map.put("all", all);
            try {
                template.process(map, response.getWriter());
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "/{placeId}/strategies", produces = "application/json")
    public Object queryStrategyByPlaceId(StrategyQueryObject qo) {
        return strategyService.queryStrategyByPlaceId(qo);

    }

}
